package timbap.visualizer.impl.context.playlist;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import timbap.visualizer.api.context.playlist.PlaylistChooser;
import timbap.visualizer.api.context.Configuration;

import javax.swing.*;
import java.io.File;
import java.io.FileFilter;

public class PopupPlaylistChooserImpl implements PlaylistChooser {

    private static final Log LOG = LogFactory.getLog(PopupPlaylistChooserImpl.class);

    private Configuration cfg;

    public PopupPlaylistChooserImpl(Configuration cfg) {
        this.cfg = cfg;
    }

    protected Configuration getCfg() {
        return cfg;
    }

    public File choosePlaylistFile() {

		File[] tPlaylistFiles = new File[0];
        if (cfg.getDefaultPlaylistDirectory().canRead()) {
			tPlaylistFiles = cfg.getDefaultPlaylistDirectory().listFiles(new FileFilter() {
				public boolean accept(File pathname) {
					return pathname.getName().endsWith(".m3u");
				}
			}
			);
		}
		if (tPlaylistFiles.length == 0) {
			LOG.error("No playlists found in directory " + cfg.getDefaultPlaylistDirectory().getAbsolutePath()
                    + ". Quitting ...");
			System.exit(0);
		}

		File tSelectedPlaylistFile = (File) JOptionPane.showInputDialog(
				null, "Select one of these playlists", "Playlist Selection for timbap",
				JOptionPane.INFORMATION_MESSAGE, null,
				tPlaylistFiles, tPlaylistFiles[0]);

		LOG.debug("Selected playlist " + tSelectedPlaylistFile.getName());
		return tSelectedPlaylistFile;

	}

}
